package com.ljp.pc.lock;

import java.util.Queue;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class Consumer implements Runnable {
    private final Queue<Integer> queue;
    private int maxSize;
    private final Condition fullCondition;
    private final Condition emptyCondition;
    private final Lock lock;

    public Consumer(Queue<Integer> queue, int maxSize, Condition fullCondition, Condition emptyCondition, Lock lock) {
        this.queue = queue;
        this.maxSize = maxSize;
        this.fullCondition = fullCondition;
        this.emptyCondition = emptyCondition;
        this.lock = lock;
    }

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                while (queue.isEmpty()) {
                    try {
                        System.out.println("队列为空，消费者(" + Thread.currentThread().getName() + ")等待生产者生产");
                        emptyCondition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                int poll = queue.poll();
                System.out.println("消费者(" + Thread.currentThread().getName() + ")消费，值为：" + poll);
                emptyCondition.signalAll();
                fullCondition.signalAll();
            } finally {
                lock.unlock();
            }
            try {
                //随机消费
                Thread.sleep(new Random().nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
